class VirtualJoystick {
  constructor(containerId) {
    this.container = document.getElementById(containerId);
    this.base = this.container.querySelector('.joystick-base');
    this.handle = this.container.querySelector('.joystick-handle');

    this.centerX = 0;
    this.centerY = 0;
    this.active = false;
    this.value = { x: 0, y: 0 };

    this.init();
  }

  init() {
    // 触摸事件
    this.container.addEventListener('touchstart', (e) => this.handleStart(e));
    document.addEventListener('touchmove', (e) => this.handleMove(e));
    document.addEventListener('touchend', (e) => this.handleEnd(e));

    // 鼠标事件（用于调试）
    this.container.addEventListener('mousedown', (e) => this.handleStart(e));
    document.addEventListener('mousemove', (e) => this.handleMove(e));
    document.addEventListener('mouseup', (e) => this.handleEnd(e));
  }

  handleStart(e) {
    this.active = true;
    const rect = this.base.getBoundingClientRect();
    this.centerX = rect.left + rect.width / 2;
    this.centerY = rect.top + rect.height / 2;
    this.handleMove(e);
  }

  handleMove(e) {
    if (!this.active) return;

    e.preventDefault();

    const point = e.touches ? e.touches[0] : e;
    const dx = point.clientX - this.centerX;
    const dy = point.clientY - this.centerY;

    const distance = Math.min(this.base.offsetWidth / 2, Math.sqrt(dx * dx + dy * dy));
    const angle = Math.atan2(dy, dx);

    const x = Math.cos(angle) * distance;
    const y = Math.sin(angle) * distance;

    this.handle.style.transform = `translate(${x}px, ${y}px)`;

    // 标准化值到-1到1之间
    this.value = {
      x: x / (this.base.offsetWidth / 2),
      y: y / (this.base.offsetWidth / 2)
    };
  }

  handleEnd() {
    this.active = false;
    this.handle.style.transform = 'translate(0px, 0px)';
    this.value = { x: 0, y: 0 };
  }

  getInput() {
    return this.value;
  }
} 